import json
from apps.pay.order.dao import OrderDao
from decimal import Decimal

def dismantleOrderByItemHandle(order):
    order = OrderDao().findOneByObjId(order.id)
    # print('order----------', order.orderId, json.loads(order.content))
    content = json.loads(order.content)
    if content.get('orderItemList') and len(content.get('orderItemList'))>0:
        res = {}
        for item in content.get('orderItemList'):
            if res.get(item.get('item')):
                res.get(item.get('item')).append(item)
            else:
                res[item.get('item')] = []
                res[item.get('item')].append(item)
        # print('res', res, res.keys())
        for key in res.keys():
            data = {
                "order": order.id,
                "scene": order.scene,
                "user": order.user.id,
                "clientname": order.clientname,
                "sendType": order.sendType,
                'addrinfo': order.addrinfo,
                'orderId': order.orderId + '-' + str(key),
                "remark": order.remark,
                "orderStatus": order.orderStatus,
                "payTime": order.payTime,
                "payway": order.payway
            }
            if order.shop:
                data['shop'] = order.shop.id
            sellingPrice = 0
            money = 0
            for item in res.get(key):
                sellingPrice = sellingPrice + Decimal(item.get('priceModel').get('sellingPrice')) * Decimal(item.get('payCount'))
                for discount in item.get('priceModel').get('discountParams'):
                    money = money + Decimal(discount.get('money'))
                
            data['sellingPrice'] = sellingPrice
            data['realPay'] = sellingPrice - money
            data['content'] = json.dumps({'orderItemList': res.get(key)})
            OrderDao().create(data)